package com.xtool.livewallpaper.local

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.ricky.epermission.runWithCameraPermission
import com.xtool.livewallpaper.R
import com.xtool.livewallpaper.base.ActivityStackManager
import com.xtool.livewallpaper.base.AlertDialog
import com.xtool.livewallpaper.base.dp
import com.xtool.livewallpaper.base.getColorCompat
import com.xtool.livewallpaper.base.getString
import com.xtool.livewallpaper.base.round
import com.xtool.livewallpaper.data.AddWallpaper
import com.xtool.livewallpaper.data.IWallpaper
import com.xtool.livewallpaper.data.LoopWallpaper
import com.xtool.livewallpaper.data.MoodWallpaper
import com.xtool.livewallpaper.data.TransparentWallpaper
import com.xtool.livewallpaper.data.VideoWallpaper
import com.xtool.livewallpaper.databinding.ItemAddBinding
import com.xtool.livewallpaper.databinding.ItemLoopBinding
import com.xtool.livewallpaper.databinding.ItemMoodBinding
import com.xtool.livewallpaper.databinding.ItemTransparentBinding
import com.xtool.livewallpaper.databinding.ItemWallpaperBinding
import com.xtool.livewallpaper.loop.LoopWallpaperActivity
import com.xtool.livewallpaper.mood.MoodWallpaperActivity
import com.xtool.livewallpaper.transparent.TransparentWallpaperActivity
import com.xtool.livewallpaper.util.SystemRouterUtil
import com.xtool.livewallpaper.util.ToastUtil
import com.xtool.livewallpaper.util.toLocalFile
import com.xtool.livewallpaper.video.VideoWallpaperActivity
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.File

abstract class BaseViewHolder<BD : ViewBinding>(open val binding: BD) :
    RecyclerView.ViewHolder(binding.root) {
}

class VideoWallpaperViewHolder(override val binding: ItemWallpaperBinding) :
    BaseViewHolder<ItemWallpaperBinding>(binding)

class AddWallpaperViewHolder(override val binding: ItemAddBinding) :
    BaseViewHolder<ItemAddBinding>(binding)

class TransparentWallpaperViewHolder(override val binding: ItemTransparentBinding) :
    BaseViewHolder<ItemTransparentBinding>(binding)

class MoodWallpaperViewHolder(override val binding: ItemMoodBinding) :
    BaseViewHolder<ItemMoodBinding>(binding)

class LoopWallpaperViewHolder(override val binding: ItemLoopBinding) :
    BaseViewHolder<ItemLoopBinding>(binding)


@Suppress("DEPRECATED_IDENTITY_EQUALS")
class WallpaperAdapter(private val load: () -> Unit) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    companion object {
        const val TYPE_TRANSPARENT = 0
        const val TYPE_VIDEO = 1
        const val TYPE_MOOD = 2
        const val TYPE_LOOP = 3
        const val TYPE_ADD = 4
    }

    private var mData: ArrayList<IWallpaper> = ArrayList()

    @SuppressLint("NotifyDataSetChanged")
    fun setData(data: ArrayList<IWallpaper>) {
        this.mData = data
        this.mData.add(0, TransparentWallpaper)
        this.mData.add(1, MoodWallpaper)
        this.mData.add(2, LoopWallpaper)
        this.mData.add(AddWallpaper)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        if (viewType === TYPE_ADD) {
            val binding = ItemAddBinding.inflate(inflater, parent, false)
            return AddWallpaperViewHolder(binding)
        } else if (viewType === TYPE_VIDEO) {
            val binding = ItemWallpaperBinding.inflate(inflater, parent, false)
            return VideoWallpaperViewHolder(binding)
        } else if (viewType === TYPE_MOOD) {
            val binding = ItemMoodBinding.inflate(inflater, parent, false)
            return MoodWallpaperViewHolder(binding)
        } else if (viewType === TYPE_LOOP) {
            val binding = ItemLoopBinding.inflate(inflater, parent, false)
            return LoopWallpaperViewHolder(binding)
        } else {
            val binding = ItemTransparentBinding.inflate(inflater, parent, false)
            return TransparentWallpaperViewHolder(binding)
        }
    }

    override fun getItemCount(): Int {
        return mData.size
    }

    override fun getItemViewType(position: Int): Int {
        return when (mData[position]) {
            is TransparentWallpaper -> TYPE_TRANSPARENT
            is MoodWallpaper -> TYPE_MOOD
            is LoopWallpaper -> TYPE_LOOP
            is AddWallpaper -> TYPE_ADD
            else -> TYPE_VIDEO
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is TransparentWallpaperViewHolder) {
            holder.binding.root.round(5f.dp)
            holder.binding.root.setOnClickListener {
                ActivityStackManager.currentActivity?.apply {
                    runWithCameraPermission(onFailed = {
                        ToastUtil.show(R.string.please_open_camera_permission)
                    }) {
                        startActivity(Intent(this, TransparentWallpaperActivity::class.java))
                        overridePendingTransition(
                            R.anim.activity_slide_in,
                            R.anim.no_anim
                        )
                    }
                }
            }
        } else if (holder is AddWallpaperViewHolder) {
            holder.binding.root.setOnClickListener {
                ActivityStackManager.currentActivity?.apply {
                    SystemRouterUtil.chooseVideo(this, { uri ->
                        launch {
                            val localFile = uri.toLocalFile()
                            val intent =
                                Intent(this@apply, VideoWallpaperActivity::class.java).apply {
                                    putExtra(
                                        VideoWallpaperActivity.VIDEO_URI,
                                        localFile?.absolutePath ?: ""
                                    )
                                }
                            startActivity(intent)
                            load()
                        }
                    })
                }
            }
        } else if (holder is MoodWallpaperViewHolder) {
            holder.binding.root.setOnClickListener {
                ActivityStackManager.currentActivity?.apply {
                    startActivity(Intent(this, MoodWallpaperActivity::class.java))
                    overridePendingTransition(
                        R.anim.activity_slide_in,
                        R.anim.no_anim
                    )
                }
            }
        } else if (holder is LoopWallpaperViewHolder) {
            holder.binding.root.setOnClickListener {
                ActivityStackManager.currentActivity?.apply {
                    startActivity(Intent(this, LoopWallpaperActivity::class.java))
                    overridePendingTransition(
                        R.anim.activity_slide_in,
                        R.anim.no_anim
                    )
                }
            }
        } else if (holder is VideoWallpaperViewHolder) {
            val binding = holder.binding
            val data = mData[position]
            (binding.ivWallpaper.layoutParams as ConstraintLayout.LayoutParams).apply {
                dimensionRatio = "1"
            }
            binding.root.round(5f.dp)
            val filePath = (mData[position] as VideoWallpaper).uri.toString()
            Glide.with(binding.ivWallpaper)
                .load(File(filePath))
                .placeholder(ColorDrawable(getColorCompat(R.color.gray)))
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(binding.ivWallpaper)
            binding.ivWallpaper.setOnClickListener {
                ActivityStackManager.currentActivity?.apply {
                    val intent =
                        Intent(this@apply, VideoWallpaperActivity::class.java).apply {
                            putExtra(
                                VideoWallpaperActivity.VIDEO_URI,
                                filePath
                            )
                        }
                    startActivity(intent)
                    overridePendingTransition(
                        R.anim.activity_slide_in,
                        R.anim.no_anim
                    )
                }
            }
            binding.ivWallpaper.setOnLongClickListener {
                val dialog = AlertDialog.AlertBuilder(binding.ivWallpaper.context)
                    .setContent(
                        getString(R.string.delete_tips)
                    )
                    .setRightText(getString(R.string.delete))
                    .setLeftText(getString(R.string.cancel))
                    .setLeftTextColor(getColorCompat(R.color.gray, binding.ivWallpaper.context))
                    .setRightTextColor(
                        getColorCompat(
                            R.color.on_surface,
                            binding.ivWallpaper.context
                        )
                    )
                    .setRightAction {
                        it.dismiss()
                        GlobalScope.launch {
                            File(filePath).delete()
                            ToastUtil.show(R.string.delete_success)
                            load()
                        }
                    }
                    .setLeftAction {
                        it.dismiss()
                    }.build()
                dialog.show()
                true
            }
        }
    }
}
